<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="formIndex"
    :title="t('routes.system.message.messageText')"
    :help-message="`${t('common.form')}：${formIndex}`"
    :showCancel="false"
    :close-func="handleClose"
    :okText="t('common.okText')"
    @ok="handleOk"
    @open-change="handleOpenChange"
    width="50%"
  >
    <template v-if="loadingRef">
      <Skeleton active />
    </template>
    <div v-else @contextmenu="handleContextMenu">
      <Row justify="space-between">
        <Col>
          <template v-if="recordRef.SenderNickname">
            <Tooltip :title="t('routes.system.message.message.senderNameText')">
              <Tag>
                <template #icon>
                  <UserOutlined />
                </template>
                {{ recordRef.SenderNickname }}
              </Tag>
            </Tooltip>
          </template>
          <template v-if="recordRef.SendTime">
            <Tooltip :title="t('routes.system.message.message.sendTimeText')">
              <Tag>
                <template #icon>
                  <FieldTimeOutlined />
                </template>
                {{ formatToDate(recordRef.SendTime, 'YYYY-MM-DD HH:mm') }}
              </Tag>
            </Tooltip>
          </template>
        </Col>
        <Col>
          <Tooltip :title="t('routes.system.message.messageTypeText')">
            <Tag
              :color="
                messageTypeEnumSchema.find((item) => {
                  return item.value === recordRef.MessageType;
                })?.tagColor
              "
            >
              {{
                messageTypeEnumSchema.find((item) => {
                  return item.value === recordRef.MessageType;
                })?.label
              }}
            </Tag>
          </Tooltip>
          <Tooltip :title="t('routes.system.message.messageLevelText')">
            <Tag
              :color="
                messageLevelEnumSchema.find((item) => {
                  return item.value === recordRef.MessageLevel;
                })?.tagColor
              "
            >
              {{
                messageLevelEnumSchema.find((item) => {
                  return item.value === recordRef.MessageLevel;
                })?.label
              }}
            </Tag>
          </Tooltip>
        </Col>
      </Row>

      <Descriptions
        :title="recordRef.Title"
        v-if="recordRef.Title || recordRef.Content"
        size="small"
        class="mt-3 msg-preview-content"
      >
        <DescriptionItem v-if="recordRef.Content">
          <Badge status="processing" :text="recordRef.Content" />
        </DescriptionItem>
      </Descriptions>

      <template v-if="recordRef.Method === 'MSG_QUERY' && recordRef.Payload">
        <PayloadPreview :value="recordRef.Payload" class="mt-1" />
      </template>
      <template v-else-if="recordRef.Method === 'MSG_NOTICE'">
        <PayloadEditor :value="recordRef.Payload" :readonly="true" class="mt-1" />
      </template>
    </div>

    <template #insertFooter>
      <a-button
        type="primary"
        color="error"
        @click="handleDeleteMessage"
        :loading="loadingRef"
        v-if="showDeletelBtn"
      >
        <Icon icon="ant-design:delete-outlined" />{{ t('common.delText') }}
      </a-button>
    </template>
  </AdVxeModal>

  <PrintTemplateModal @register="templateModalRegister" v-bind="templateModalProps" />
</template>

<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref } from 'vue';
  import { Row, Col, Descriptions, Tag, Badge, Skeleton, Tooltip } from 'ant-design-vue';
  import { UserOutlined, FieldTimeOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '@/hooks/web/useMessage';

  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import Icon from '@/components/Icon/Icon.vue';
  import { PrintTemplateModal, useAdPrint } from '@/components/AdPrint';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useContextMenu } from '@/hooks/web/useContextMenu';
  import { destroyContextMenu } from '@/components/ContextMenu';
  import { isFunction } from '@/utils/is';
  import { formatToDate } from '@/utils/dateUtil';

  import { getMessageTypeEnumSchema } from '@/enums/messageTypeEnum';
  import { getMessageLevelEnumSchema } from '@/enums/messageLevelEnum';

  import { MessageDto } from '@/api/message/model';
  import { getMessageDetails, readMessages, deleteMessages } from '@/api/message';

  import PayloadPreview from '@/views/system/message/querymessage/PayloadPreview.vue';
  import PayloadEditor from '@/views/system/message/templatemessage/PayloadEditor.vue';

  const DescriptionItem = Descriptions.Item;

  defineOptions({ name: 'MessagePreviewModal' });
  const props = defineProps({
    /** 显示关闭按钮 */
    showDeletelBtn: { type: Boolean, default: true },
    /** 关闭回调，返回true关闭窗体 */
    closeFunc: {
      type: Function as PropType<(record: MessageDto | undefined) => Promise<boolean>>,
      default: null,
    },
    /** 确认回调，返返回true关闭窗体 */
    okFunc: {
      type: Function as PropType<(record: MessageDto | undefined) => Promise<boolean>>,
      default: null,
    },
  });
  const emit = defineEmits(['delete-message', 'load-complete', 'register']);

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const [createContextMenu] = useContextMenu();
  const recordRef = ref<any>({});
  const formIndex = 'message_detail_preview';
  const keyField = 'Id';

  const [register, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
    recordRef.value = {};
    openLoading();
    try {
      const recordId = data.record?.Id;
      if (recordId) {
        if (data.request) {
          const result = await getMessageDetails({
            RequestWay: 1,
            MessageIds: [recordId],
          });
          const record = result.Data;
          if (record?.length > 0) {
            setMessageDto({
              ...record[0],
            });
          }
        } else {
          setMessageDto({
            ...data.record,
          });
          await readMessages({
            RequestWay: 1,
            MessageIds: [recordId],
            Read: true,
          });
        }
      }
    } finally {
      emit('load-complete', getMessageDto());
      closeLoading();
    }
  });

  //#region "加载状态"
  const loadingRef = ref(false);
  /** 开启加载状态 */
  function openLoading() {
    changeLoading(true);
    setModalProps({ okLoading: true, cancelLoading: true });
    loadingRef.value = true;
  }
  /** 关闭加载状态 */
  function closeLoading() {
    changeLoading(false);
    setModalProps({ okLoading: false, cancelLoading: false });
    loadingRef.value = false;
  }
  //#endregion
  //#region 定义高级打印
  const { printContextMenus, templateModalRegister, templateModalProps } = useAdPrint({
    formIndex: formIndex,
    keyField: keyField,
    getFormData: () => getMessageDto(),
  });
  /** 处理上下文菜单(右键菜单) */
  function handleContextMenu(e: MouseEvent) {
    const element = document.elementFromPoint(e.clientX, e.clientY) as Element;
    const cursor = document.defaultView?.getComputedStyle(element, null).cursor;
    // console.log('handleContextMenu', {
    //   cursor: cursor,
    // });

    let items: any[] = [];
    if (!cursor || cursor === 'default' || cursor === 'auto') {
      items = [...printContextMenus];
    }
    if (items && items?.length > 0) {
      createContextMenu({
        event: e,
        styles: {
          border: '1px solid #eee',
          'border-radius': '2px',
          'box-shadow': '3px 3px 3px rgb(0 0 0 / 15%)',
        },
        items: [...items],
      });
    }
  }
  //#endregion

  /** 获取消息DTO */
  function getMessageDto(): MessageDto {
    const record = (recordRef.value || {}) as MessageDto;
    return record;
  }
  /** 设置消息DTO */
  function setMessageDto(values: any) {
    recordRef.value = {
      ...(recordRef.value || {}),
      ...values,
    };
  }

  /** 处理关闭按钮 */
  async function handleClose() {
    openLoading();
    const { closeFunc } = props;
    try {
      if (closeFunc && isFunction(closeFunc)) {
        const dto = getMessageDto();
        const result = await closeFunc(dto);
        return result;
      }
    } finally {
      closeLoading();
    }
    return true;
  }
  /** 处理确定按钮 */
  async function handleOk() {
    openLoading();
    const { okFunc } = props;
    try {
      if (okFunc && isFunction(okFunc)) {
        const dto = getMessageDto();
        const result = await okFunc(dto);
        if (result) {
          closeModal();
        }
      } else {
        closeModal();
      }
    } finally {
      closeLoading();
    }
  }
  /** 打开或者关闭触发 */
  function handleOpenChange(open: boolean) {
    if (!open) {
      destroyContextMenu();
    }
  }

  /** 处理删除 */
  async function handleDeleteMessage() {
    const dto = getMessageDto();
    if (dto?.Id) {
      openLoading();
      try {
        var reulst = await deleteMessages([dto.Id]);
        if (reulst.Succeeded) {
          createMessage.success(t('common.successText'));
          emit('delete-message', dto);
          closeModal();
        }
      } finally {
        closeLoading();
      }
    }
  }

  const messageTypeEnumSchema = getMessageTypeEnumSchema();
  const messageLevelEnumSchema = getMessageLevelEnumSchema();
</script>

<style lang="less">
  .msg-preview-content {
    .ant-descriptions-header {
      margin-bottom: unset !important;
    }
  }
</style>
